import os
# 禁用所有可能导致AVX512指令的优化
os.environ["FLAGS_use_mkldnn_conv_self_attn_fuse"] = "false"
os.environ["FLAGS_use_mkldnn"] = "false"
os.environ["FLAGS_use_mkldnn_conv"] = "false"
os.environ["FLAGS_use_mkldnn_matmul"] = "false"
os.environ["FLAGS_use_mkl"] = "false"
os.environ["FLAGS_use_avx"] = "false"
os.environ["FLAGS_use_avx2"] = "false"
os.environ["FLAGS_use_avx512"] = "false"
os.environ["FLAGS_use_fma"] = "false"
os.environ["FLAGS_use_f16c"] = "false"

import fastapi
import uvicorn
from paddleocrPdfDeal import router_paddle_ocr
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

# 确保模型目录结构存在
current_dir = os.path.dirname(os.path.abspath(__file__))
models_dir = os.path.join(current_dir, "custom_models")

# 创建模型目录结构
os.makedirs(os.path.join(models_dir, "det"), exist_ok=True)
os.makedirs(os.path.join(models_dir, "rec"), exist_ok=True)
os.makedirs(os.path.join(models_dir, "cls"), exist_ok=True)

# 确保前端目录存在
front_dir = os.path.join(current_dir, "front")
os.makedirs(front_dir, exist_ok=True)

app = fastapi.FastAPI()

# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，生产环境应该更严格
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="front"), name="static")

# 添加根路由，返回前端页面
@app.get("/")
async def read_root():
    return FileResponse("front/index.html")

# 添加paddleocr281.html的专门路由
@app.get("/paddleocr281.html")
async def read_paddleocr_page():
    return FileResponse("front/paddleocr281.html")

# 逐个绑定路由，并指定前缀
app.include_router(router_paddle_ocr, prefix="/paddle_ocr")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
